﻿using System;
using System.Collections.Generic;
using System.Linq;
using EmployeeApp.DAL.Entities;
using EmployeeApp.DAL.Models.Employee;
using NHibernate;
using NHibernate.Criterion;

namespace EmployeeApp.DAL.Dal
{
    public class EmployeeDAL
    {
        public ISession session;
        public EmployeeDAL(ISession session)
        {
            this.session = session;
        }

        public List<Employee> GetAll(SearchCriteria searchCriteria)
        {
            var criteria = session.CreateCriteria(typeof(Employee));

            if (searchCriteria != null)
            {
                // Search
                if (!string.IsNullOrEmpty(searchCriteria.EmpId))
                {
                    criteria.Add(Expression.Like("EmpId", searchCriteria.EmpId, MatchMode.Start));
                }
                if (!string.IsNullOrEmpty(searchCriteria.Name))
                {
                    criteria.Add(Expression.Like("Name", searchCriteria.Name, MatchMode.Start));
                }
                if (searchCriteria.Status > 0)
                {
                    criteria.Add(Expression.Eq("Status", searchCriteria.Status));
                }

                //Sort
                if (!string.IsNullOrEmpty(searchCriteria.Sort))
                {
                    if (!string.IsNullOrEmpty(searchCriteria.SortType) && searchCriteria.SortType.ToLower() == "desc")
                    {
                        criteria.AddOrder(Order.Desc(searchCriteria.Sort));
                    }
                    else
                    {
                        criteria.AddOrder(Order.Asc(searchCriteria.Sort));
                    }

                }
            }

            return criteria.List<Employee>().ToList();
        }

        public void Add(Employee employee)
        {
            session.Save(employee);
        }

        public void Update(Employee employee)
        {
            // todo: temp fix problem ==> 
            // a different object with the same identifier value was already associated with the session: 3, 
            // of entity: EmployeeApp.DAL.Entities.Employee
            employee = session.Merge(employee);
            session.Update(employee);
        }

        public void Delete(List<string> idList)
        {
            int row = session.CreateQuery("DELETE Employee where Id in (:IdList)").SetParameterList("IdList", idList).ExecuteUpdate();
            if (row != idList.Count)
                throw new Exception("Delete Not Success");

        }
    }
}
